<!--
 * @PageName: 
 * @Description: 
 * @FilePath: /glm-mes-pc/src/views/Demo/components/tableComponent.vue
-->
<template>
	<div class="common-table-container" style="padding-top: 16px">
		<div style="margin-bottom: 10px">
			<el-button type="primary" @click="receiveOrders" :disabled="!selected.length" :loading="receiveOrdersLoading" v-if="queryParams.orderStatus == 0">批量接单</el-button>
			<el-button type="primary" @click="createForm">创建表单</el-button>
		</div>
		<!-- 表格区 -->
		<el-table
			:data="tableData"
			v-adaptive
			v-loading="loading"
			border
			tooltip-effect="light"
			@sort-change="handleSortChange"
			ref="tableRef"
			:header-cell-style="{ 'text-align': 'center' }"
			scrollbar-always-on
			@selection-change="handleSelectionChange"
		>
			<template v-for="(column, index) in columns" :key="column.prop">
				<el-table-column
					:prop="column.prop"
					:label="column.label"
					:sortable="column.sortable"
					:width="column.width"
					:align="column.align"
					show-overflow-tooltip
					:fixed="column.fixed"
					:type="column.type"
					v-if="tabsShowJudge(column.tabsShow, queryParams.orderStatus) && excludeRole(column.excludeRole)"
				>
					<!-- 表头筛选 -->
					<template v-if="column.filter" #header="scope">
						<!-- 筛选组件 -->
						<TableFilter
							:headerTitle="column.label"
							:headerProp="column.prop"
							:filterLoading="filterLoading"
							:ref="(el) => setFilterRef(el, index)"
							:isActive="activeFilter === index"
							:activeIndex="index"
							:filterOptions="filterOptions"
							@toggleFilter="toggleFilter"
							@resetActiveFilter="setActiveFilter(null)"
							@updateStorageFilterObject="updateStorageFilterObject"
							@removeCurrentCondition="removeCurrentCondition"
						/>
					</template>
					<!-- 使用 template 和 slot 来判断是否需要自定义渲染 -->
					<template v-if="column.customRender" #default="scope">
						<!-- 判断列类型，根据类型决定渲染内容 -->
						<!-- 序号 -->
						<span v-if="column.type === 'index'">{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>

						<!-- 操作列 -->
						<div v-if="column.type === 'operation'"></div>
					</template>

					<!-- 没有自定义渲染时，使用默认渲染 -->
					<!-- <template v-else #default="scope">
						{{ scope.row[column.prop] }}
					</template> -->
				</el-table-column>
			</template>
		</el-table>

		<!-- 分页区 -->
		<pagination
			v-show="total > 0"
			:total="total"
			v-model:page="queryParams.pageNum"
			v-model:limit="queryParams.pageSize"
			@pagination="paginationHandel"
			:disabled="changeLock"
			:pageSizes="[50, 100, 200, 500]"
		/>

		<!-- 创建表单弹窗 -->
		<CreateFormDialog ref="createFormDialogRef" v-model:dialogVisible="createFormVisible" />
	</div>
</template>

<script setup>
import CreateFormDialog from './createFormDialog'
import { checkRole } from '@/utils/permission'
import { downloadFileWithCustomName } from '@/utils/index.js'
import { camelToSnakeCase, tabsShowJudge, excludeRole } from '@/utils/index'
import { receiveInspectionOrderAPI, getInspectionListAPI as filterConditionsAPI, getPurchaseNumberAPI } from '@/api/inspectionInfo.js'
// 引入表格筛选组合式函数
import { useFilterManagement } from '@/utils/useFilterManagement'
const { filterRefs, activeFilter, storageFilterObject, setActiveFilter, setFilterRef, updateStorageFilterObject, removeStorageFilterObject, clearStorageFilterObject } = useFilterManagement()
const router = useRouter()

const { proxy } = getCurrentInstance()
let props = defineProps({
	queryParams: Object,
	total: Number,
	loading: Boolean,
	tableData: Object,
	changeLock: Boolean
})
let { queryParams, total, loading, tableData, changeLock } = toRefs(props)

const tableRef = ref(null)
/* 表格列配置 */
const columns = ref([
	{
		width: '40',
		type: 'selection',
		fixed: 'left',
		tabsShow: [0]
	},
	{
		align: 'center',
		label: '序号',
		width: '55',
		// 自定义渲染列
		customRender: true,
		// 索引类型
		type: 'index'
	},
	{
		prop: 'orderNum',
		align: 'center',
		width: '160',
		label: '检品订单号',
		filter: true
	},
	{
		prop: 'saleOrderId',
		align: 'center',
		width: '150',
		label: '销售订单号',
		filter: true
	},
	{
		prop: 'styleNumber',
		align: 'center',
		width: '100',
		label: '款号',
		filter: true
	},
	{
		prop: 'materialName',
		align: 'left',
		width: '140',
		label: '物料名称',
		filter: true
	},
	{
		prop: 'totalQty',
		align: 'right',
		label: '数量',
		sortable: 'custom'
	},
	{
		prop: 'unitPrice',
		align: 'right',
		width: '110',
		label: '检品单价',
		sortable: 'custom',
		excludeRole: ['jpgsyg']
	},
	{
		prop: 'totalMoney',
		align: 'right',
		width: '110',
		label: '总金额',
		sortable: 'custom',
		excludeRole: ['jpgsyg']
	},
	{
		prop: 'supplierName',
		align: 'center',
		width: '140',
		label: '送货工厂',
		filter: true
	},
	{
		prop: 'planEntryTime',
		align: 'left',
		width: '160',
		label: '预计到货日期',
		sortable: 'custom',
		filter: true
	},
	{
		prop: 'expectedBoxTime',
		align: 'left',
		width: '160',
		label: '预计完工日期'
	},
	{
		prop: 'rejectStatus',
		align: 'center',
		width: '120',
		label: '工艺资料',
		// 自定义渲染列
		customRender: true,
		// 索引类型
		type: 'file'
	},
	{
		align: 'center',
		label: '操作',
		width: '160',
		// 自定义渲染列
		customRender: true,
		// 操作类型
		type: 'operation',
		fixed: 'right'
	}
])

const tableRowClassName = ({ row, rowIndex }) => {
	if (rowIndex === 0) {
		return 'warning-row'
	}
	return ''
}
const dialogRef = ref(null)
const dialogVisible = ref(false)
const selected = ref([])
const receiveOrdersLoading = ref(false)
const uploadIsShow = ref(false)
const fileList = ref([])
const fileDetailDialogVisble = ref(false)
const fileUrl = ref('')
const fileName = ref('')
const contractVisible = ref(false)
const contractInfo = ref({})
const coontractTableData = ref([])
const emits = defineEmits(['pagination', 'sort'])

const paginationHandel = () => {
	emits('pagination', storageFilterObject.value)
}

const createFormVisible = ref(false)
const rowInfo = ref({})
const createFormDialogRef = ref(null)
// 显示创建表单弹窗
const createForm = () => {
	createFormVisible.value = true
	createFormDialogRef.value.handleFormData(null)
}

/* 下载功能 */
const handleDownloadFile = async (item) => {
	downloadFileWithCustomName(item.uploadUrl, item.uploadName)
}

/* 多选 */
const handleSelectionChange = (val) => {
	selected.value = val.map((item) => item.orderNum)
}

/* 批量接单 */
const receiveOrders = () => {
	proxy.$modal
		.confirm('确定要批量接单吗？')
		.then(async () => {
			receiveOrdersLoading.value = true
			const res = await receiveInspectionOrderAPI({
				orderNums: selected.value
			})
			if (res.code === 200) {
				receiveOrdersLoading.value = false
				proxy.$modal.msgSuccess('批量接单成功')
				paginationHandel()
			}
		})
		.catch((error) => {})
}

/* 排序 */
const handleSortChange = ({ prop, order, column }) => {
	// 如果sortable属性为true采用前端排序
	const filterTarget = columns.value.filter((item) => item.prop === prop)[0]
	if (filterTarget.sortable === true) {
		return
	}
	// sortable属性为custom采用后端排序
	const orderByColumn = order ? camelToSnakeCase(prop) : ''
	const isAsc = order ? (order === 'ascending' ? 'asc' : order === 'descending' ? 'desc' : '') : ''
	emits('sort', orderByColumn, isAsc)
}
/* 重置排序 */
const clearSort = () => {
	tableRef.value.clearSort()
}

/**
 * @description: 从存储中移除当前筛选列的配置并刷新表格列表
 * @event:
 * @param {Stinr} beforeName 小驼峰字段名+'s'
 * @return {*}
 */
const removeCurrentCondition = (beforeName) => {
	removeStorageFilterObject(beforeName)
	emits('pagination', storageFilterObject.value)
}

/* 关闭弹窗供父组件使用 */
const closeActiveFilter = () => {
	setActiveFilter(null)
}

/**
 * @description: 切换筛选列
 * @event:
 * @param {Number} index 当前要显示的筛选弹窗索引
 * @param {String} name 小驼峰转下划线写法后的字段名
 * @param {String} beforeName 小驼峰字段名+'s'
 * @return {*}
 */
const toggleFilter = (index, name, beforeName) => {
	if (activeFilter.value === index) {
		// 第二次点击相同筛选列关闭该弹窗
		setActiveFilter(null)
	} else {
		// 显示筛选弹窗
		setActiveFilter(index)
		// 如果本地点击的筛选列之前已经筛选过，需要清空掉本列之前携带的筛选参数
		if (filterRefs.value[index].isFiltered) {
			const copyStorageFilterObject = JSON.parse(JSON.stringify(storageFilterObject.value))
			copyStorageFilterObject[beforeName] && delete copyStorageFilterObject[beforeName]
			// 获取筛选列表数据
			getFilterConditions(name, copyStorageFilterObject)
		} else {
			getFilterConditions(name, storageFilterObject.value)
		}
	}
}

const filterOptions = ref([])
const filterLoading = ref(false)

/**
 * @description: 获取筛选列表数据
 * @event:
 * @param {String} name 小驼峰转下划线写法后的字段名
 * @param {Object} target 筛选集合，格式例子：{supplier：['', '', ''],orderId: ['', '', '']}
 * @return {*}
 */
const getFilterConditions = async (name, target) => {
	filterLoading.value = true
	const res = await filterConditionsAPI({ field: name }, { ...queryParams.value, pageNum: 1, pageSize: 99999, ...target })
	// 将后端返回的map形式数据处理成前端对象形式
	filterOptions.value = Object.keys(res.data).map((key) => {
		return {
			id: key,
			label: res.data[key]
		}
	})
	filterLoading.value = false
}

/* 重置所有筛选 */
const batchResetFilter = () => {
	clearStorageFilterObject()
	// 循环ref重置每个筛选项基础数据
	filterRefs.value.forEach((item) => {
		item.resetBaseFilterInfo()
	})
}

defineExpose({
	clearSort,
	batchResetFilter,
	storageFilterObject,
	closeActiveFilter
})
</script>

<style lang="scss" scoped>
:deep(.el-table .warning-row) {
	--el-table-tr-bg-color: var(--el-color-warning-light-9);
	--el-bg-color: var(--el-color-warning-light-9);
}
.blue {
	color: #265bae;
}
.blue:hover {
	color: #409eff;
}
.file-dialog-content {
	max-height: 400px;
	overflow: auto;
}
.file-item {
	font-size: 12px;
	color: #061326;
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 10px;
	.file-content {
		display: flex;
		.svg-icon {
			font-size: 36px;
		}
		.name-creator-tiem {
			margin-left: 6px;
			.creator-tiem {
				display: flex;
				span:last-child::before {
					content: ':';
					margin-right: 5px;
				}
				.creator {
					margin-right: 10px;
				}
			}
		}
	}
}
.file-right {
	margin-right: 10px;
	color: #265bae;
	cursor: pointer;
	.look::after {
		content: '｜';
		margin: 0 5px;
	}
}
</style>
